package de.htwg.memory.activity;

import java.io.IOException;

import org.json.*;

import de.htwg.memory.CheckCards;
import de.htwg.memory.Connection;
import de.htwg.memory.IConnection;
import de.htwg.memory.MemoryCard;
import de.htwg.memory.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

/**
 * this class represent a game card, which can be clicked and turned each card has a common backimage
 * two cards with the same cardid have the same unique frontimage
 * 
 * @author Benjamin Moellerke <bemoelle@googlemail.com>
 * @version V1.0 06-06-2012
 * 
 */
public class GameActivity extends Activity {
	

	private TableLayout table;
	private Context contextTable;
	private int x = 0;
	private int y = 0;
	private TextView anzTries;
	private Integer anz = 0;
	private GameActivity gameActivity;
	private String name;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
        setContentView(R.layout.game);
        
        table = (TableLayout)findViewById(R.id.tableLayout1);
        contextTable = table.getContext();  
        
        anzTries = (TextView)findViewById(R.id.anz);
        anzTries.setText("0");
        
        //forwarder parameters from StartActivity.class
        String size = (String) getIntent().getExtras().get("size");       
        name = (String) getIntent().getExtras().get("name");
        
        TextView nameView = (TextView)findViewById(R.id.nameText);
        nameView.setTextColor(0xFF000000);
        nameView.setText(name);
        
        gameActivity = this;
        
        //set size of memory board
        //necessary because forwarded size is an string
        if("4x4".equals(size)) {
        	x=4;
        	y=4;
        }
        else {
        	x=6;
        	y=6;
        }
               
        //create new game
        try {
        	createNewGame(x, y);
        }
        catch (Exception e) {
        	Log.e("Exception GameActivity", "createGame failed");
        	AlertDialog.Builder builder = new AlertDialog.Builder(gameActivity);
    		builder.setTitle("ERROR")
    		       .setCancelable(false)
    		       .setMessage("cannot create a new game - no connection to server")
    		       .setPositiveButton("Close", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		        	   gameActivity.finish();
    		           }
    		       });
    		
    		AlertDialog alert = builder.create();
    		alert.show();
		}
    }
    
    /**
     * @return playername
     */
    public String getName() {
    	
    	return name;
    }
    
    /**
     * @return count of tries
     */
    public int getTries() {
    	
    	return anz;
    }
    
    /**
     * create an new game
     *       
     * @param row number of rows in the memory game
     * @param col number of columns in the memory game
     * @throws IOException exception from readMemory()
     * @throws JSONException exception from readMemory()
     */
    private void createNewGame(final int row, final int col) throws JSONException, IOException {
    	
    	//create new connection
    	final IConnection connection = new Connection();
    	
    	//create a new memorycard array
    	final MemoryCard[] cards = new MemoryCard[row*col];
    	
    	//send an http request to the webserver to get the ids for the memorycards
    	JSONArray jsonArray = connection.readMemory(row, col);
    	
    	
    	//error Message if connection is interrupted
    	if(jsonArray == null) {
    		
        	AlertDialog.Builder builder = new AlertDialog.Builder(gameActivity);
    		builder.setTitle("ERROR")
    		       .setCancelable(false)
    		       .setMessage("cannot create a new game - no connection to server")
    		       .setPositiveButton("Close", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		        	   gameActivity.finish();
    		           }
    		       });
    		
    		AlertDialog alert = builder.create();
    		alert.show();
		}
    	
    	  	
    	//fill the table layout with memory cards
    	for(int i=0; i<row; i++) {
    		
    		//create a new tabelrow in the table layout
    		final TableRow tr = new TableRow(this);
    	    tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    	    
       	    for(int j=0; j<col; j++) {
    	    	
       	    	//get id for current memory card
    	    	int id = jsonArray.getJSONArray(i).getInt(j);
    	    	
    	    	//create new memorycard and set it clickable
    	    	final MemoryCard card = new MemoryCard(contextTable, id);
    	    
    	    	card.setOnClickListener(new OnClickListener() {

    				public void onClick(View arg0) {
    				       					
    					if(!card.isClicked()) {
    						card.setWantToTurn(true);
    						card.setTurnBack(0);
       					}
    					
    					else if(card.getTurnBack() == 1) {
    						anz++;
    						anzTries.setText(anz.toString());
    						card.setTurnBack(2);
    					}
    					//after a card is clicked start a asynctask to check whether 
    					//two cards are clicked
    					//equal -> cards disappear
    					//unequal -> turn arround cards
    					new CheckCards(gameActivity, connection, cards, row, col).execute();
    				}});
    	    	//add card to tablerow
    	    	tr.addView(card);
    	    	//and set card in array
    	    	cards[(row*i)+j] =card;
    	    }
       	    //set tablerow to tablelayout
    	    table.addView(tr);
    	}  
    }       
}
